<template>
  <div class="fileUpload">
    <a-upload v-model:file-list="fileList" :before-upload="beforeUpload" @change="handleChange"
      :custom-request="(file: otherType, fileList: any) => handleUpload(file)" multiple="true" :progress="progress">
      <div v-if="props.listType == 'text'">
        <a-button class="upload_button_line" :disabled="props.maxCount ? fileList.length >= props.maxCount : false"
          v-if="props.listType == 'text'">
          <upload-outlined></upload-outlined>
          <i class="iconfont icon-upload" style="font-size: 16px;color:#000000D9;margin-right: 8px;"> </i>
          {{ props.title }}
        </a-button>
        <div class="tips" v-if="props.accept && !props.hiddTips">支持{{ props.accept }}格式</div>
      </div>
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, computed, nextTick, onMounted, reactive } from "vue";
import { message } from "ant-design-vue";
import { baseUploadProps } from "./uploadConfig/props";
import { dataSourceType } from "../../type";
import { request } from "@/api/axios";
import { t } from "vxe-table";
//import request from "@/api/index";
//props
const props = defineProps(baseUploadProps);

//emit
const emit = defineEmits([
  "uploadChangeFinished",
  "uploadFinished",
  "upload_remove_Finished",
]);
//type
type otherType = {
  [propName: string]: any;
};
//data
const fileList = ref<dataSourceType[]>([]);
const optionsList = ref<dataSourceType[]>([]);
let acceptTypeList = ref<string[]>([]);
let styles = ref<string>("");
const pp = ref<string | number>(0);
  const progress = reactive({
  strokeColor: {
    '0%': '#108ee9',
    '100%': '#87d068',
  },
  strokeWidth: 3,
  format: (percent: number) => {
    return `${parseFloat((+percent).toFixed(0))}%`;
  },
  class: 'test',
});
//watch
watch(
  () => props.fileList,
  (newVal, oldVal) => {
    console.log('附件！！！', newVal)
    if (newVal.length) {
      fileList.value = newVal;
      nextTick(() => {
        getImageStyle(newVal[0].url);
      })

    } else {
      fileList.value = [];
    }
  },
  { deep: true, immediate: true }
);
//methods
const getImageStyle = (src: string) => {
  const url = src;
  if (url) {
    var img = new Image();
    img.src = url;
    img.onload = function () {
      console.log(img.naturalWidth, img.naturalHeight, 9999);
      if (img.naturalWidth >= img.naturalHeight) {
        styles.value = `width:100%;height:auto`;
      } else {
        styles.value = `width:auto;height:100%`;
      }
    };
  }
};

const handleUpload = (options: otherType) => {
  // 上传到服务器

  // optionsList.value.push()
  const param = new FormData(); // 创建form对象
  param.append("files", options.file, options.file.name); // 通过append向form对象添加数据
  // param.append("noWatermark", "1");
  // param.append("toConvertPdf", "1");
  if (props.isAutoUpload) {
    // props.isAutoUpload 用来判断是否能直接上传，若不能，需要用emit传递出formData数据到调取处

    options.file.status = "success";
    //  request.fetchsiteManageGetSiteDetail_upload(param,
    //  	{
    //  	onUploadProgress: ({ total, loaded }) => {
    //        options.onProgress({ percent: Math.round((loaded / total) * 100).toFixed(2) }, options);
    //    },
    //  }
    //
    //  ).then((res: otherType) => { //直接调接口222
    //    if (res.code === '00000 00000') {
    ////    	options.onProgress({percent:100})
    ////    	progress.format(100)
    ////    	options.file.status = 'success';
    ////
    //  	 options.onSuccess(res.data, options.file);
    //    	setTimeout(()=>{
    //    		//fileList.value.push(options.file);
    //
    //        emit('uploadFinished', res.data);
    //    	}, 10000)
    //
    //    }
    //  })
    // 要放在global
    request
      .post("/server-admin/res/upload", param, {
        headers: {
          "Content-Type":
            "multipart/form-data; boundary=----WebKitFormBoundary1kBB8pgsKICPa9RM",
        },
        onUploadProgress: ({ total, loaded }) => {

          if (total) {
            pp.value =
              Math.round((loaded / total) * 100) < 100
                ? Math.round((loaded / total) * 100).toFixed(1)
                : (100 - Math.random() * 10).toFixed(1);
            if (options.onProgress) {
              //留足大图片渲染时间
              options.onProgress(
                { percent: Math.round((loaded / total) * 100).toFixed(2) },
                options
              );
            }
          }
        },
      })
      .then((res: any) => {
        if (res.data.code == "00000 00000") {
          pp.value = 100;
          if (options.onSuccess) {
            options.onSuccess(res.data.data, options);
          }

          emit("uploadChangeFinished", ...res.data.data);
          message.success(res.data.message);
        } else {
          message.error(res.data.message);
          if (options.onError) {
            options.onError(res.data.data, options);
          }
          fileList.value = [];
        }
      })
      .catch((err) => {
        console.log(err, 9999);
      });
  } else {
    options.onProgress({ percent: 100 });
    console.log(options,'options啦啦啦');
    
    emit("uploadChangeFinished", options);
  }
};

// const handleOk = () => {
//   console.log(e);
// };
// computed
acceptTypeList = computed({
  get() {
    return props.accept ? props.accept.split(",") : [];
  },
  set() { },
});
</script>
<style lang="less" scoped>
.fileUpload {
  ::v-deep(.ant-upload-text-icon) {
    display: none;
  }
}


.upload_button_line {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.tips {
  margin-top: 8px;
  color: rgba(0, 0, 0, 0.45);
  line-height: 20px;
  font-size: 12px;
}
</style>
<style lang="less">
.ant-form-horizontal .ant-form-item-control {
  width: calc(100% - 92px);
}
.fileUpload {
  .ant-progress-text {
    position: absolute;
    top: -5px;
    right: 25px;
  }
}
</style>
